package com.qingcloud.adminbackend.base;

import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.util.Arrays;


/**
 * vue-table2分页查询参数
 */
public class Vuetable2PageParams implements Serializable {

    @ApiModelProperty(value = "排序字符串，字段|顺序", example = "stationId|asc")
    private String sort;

    @ApiModelProperty(value = "每页条数", example = "10")
    private Integer perPage;

    @ApiModelProperty(value = "查询页码，从1开始", example = "1")
    private Integer page;

    @ApiModelProperty(value = "查询偏移位置", example = "0", hidden = true)
    private Long offset;

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public String getOrderByCause(String[] allowFields) {
        //convert sort order by cause, using allowFields, filter sql Injection.
        StringBuilder orderBy = new StringBuilder();
        if (sort != null && !"".equals(sort)) {
            java.util.List<String> allowfdList = Arrays.asList(allowFields);
            String[] sorts = sort.split(",");
            for (String sortStr : sorts) {
                String[] sfield = sortStr.split("\\|");
                if (sfield.length > 0 && allowfdList.indexOf(sfield[0]) >= 0) {
                    orderBy.append(sfield[0]);
                    if (sfield.length > 1 && (sfield[1].equalsIgnoreCase("asc") || sfield[1].equalsIgnoreCase("desc")))
                        orderBy.append(" ").append(sfield[1]);
                    orderBy.append(',');
                }
            }
        }
        if (orderBy.length() > 0)
            orderBy.setLength(orderBy.length() - 1);
        return orderBy.toString();
    }

    public Integer getPerPage() {
        return perPage;
    }

    public void setPerPage(Integer perPage) {
        this.perPage = perPage;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Long getOffset() {
        return Long.valueOf((page - 1) * (long)perPage);
    }
}

